package com.dzsw.netty.basic.nio;

import com.google.common.base.Strings;

import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.IntBuffer;

public class BasicBuffer {

    public static void main(String[] args) {
//        intBufferDemo();
        byteBufferDemo();
    }

    public static void intBufferDemo() {
        IntBuffer buff = IntBuffer.allocate(5);

        for (int i = 0; i < buff.capacity(); i++) {
            buff.put(i * 2);
        }

        buff.flip();

        for (int i = 0; i < buff.limit(); i++) {
            System.out.println(Strings.lenientFormat("------ value = %s ------", buff.get()));
            printBufferInfo(buff);
            System.out.println("");
        }

        buff.rewind();

        while (buff.hasRemaining()) {
            System.out.println(Strings.lenientFormat("------ value = %s ------", buff.get()));
            printBufferInfo(buff);
            System.out.println("");
        }
    }

    public static void byteBufferDemo() {
        // 创建缓冲区
        ByteBuffer buff = ByteBuffer.allocate(1024);
        System.out.println("-----allocate-----");
        printBufferInfo(buff);
        System.out.println("");
        // 存入数据
        System.out.println("-----put-----");
        buff.put("I'm sorry.".getBytes());
        printBufferInfo(buff);
        System.out.println("");
        // 切换成读模式
        System.out.println("-----flip-----");
        buff.flip();
        printBufferInfo(buff);
        System.out.println("");
        // 读数据
        System.out.println("-----get-----");
        byte[] temp = new byte[buff.limit()];
        buff.get(temp);
        System.out.println(new String(temp));
        printBufferInfo(buff);
        System.out.println("");
        // 重复读
        System.out.println("-----rewind-----");
        buff.rewind();
        printBufferInfo(buff);
        System.out.println("");
        // mark
        System.out.println("-----mark-----");
        System.out.println(buff.get());
        System.out.println(buff.get());
        buff.mark();
        System.out.println(buff.get());
        System.out.println(buff.get());
        printBufferInfo(buff);
        buff.reset();
        printBufferInfo(buff);
        // 清空缓冲区
        System.out.println("-----clear-----");
        buff.clear();
        printBufferInfo(buff);

    }

    private static void printBufferInfo(Buffer buff) {
        System.out.println(Strings.lenientFormat("position = %s", buff.position()));
        System.out.println(Strings.lenientFormat("limit = %s", buff.limit()));
        System.out.println(Strings.lenientFormat("capacity = %s", buff.capacity()));
    }
}
